iT邦幫忙

0

【C#】Number Random

c#
  • 分享至 

  • xImage
  •  

這次我們來看到C#亂數的實務應用拉~ Random.Next()~

它又分為三種方向~ 分別是 Next()~ Next(100)~ Next(100, 200)~

這次的亂數實務比較複雜一點lol~ 因為寫了不重複例外錯誤的功能~


學習目標: Number Random 實務

學習難度: ☆☆☆


using System;

using System.Collections.Generic;

namespace ConsoleApp1
{
    class NumberRandom
    {
        public void RandomFucntion(int MiniNumber, int MaxNumber, int guessnumber)
        {
            Random randomrange = new Random();

            List<int> RandomCandiate = new List<int>();

            for (int i = 0; i < guessnumber; i++)
            {
                RandomCandiate.Add(randomrange.Next(MiniNumber, MaxNumber));

                for (int j = 0; j < i; j++)
                {
                    while (RandomCandiate[j] == RandomCandiate[i])
                    {
                        j = 0;

                        RandomCandiate[i] = randomrange.Next(MiniNumber, MaxNumber);
                    }
                }
                Console.WriteLine(RandomCandiate[i]);
            }
        }
    }

    class MainProgram
    {
        static void Main()
        {
            NumberRandom numberrandom = new NumberRandom();

            try
            {
                Console.WriteLine("Please input mini num");

                int MiniNumber = int.Parse(Console.ReadLine());

                if (MiniNumber < 0)
                {
                    throw new ArgumentOutOfRangeException();
                }

                Console.WriteLine("Please input max num");

                int MaxNumber = int.Parse(Console.ReadLine());

                Console.WriteLine("Please input how many  num you wana guess");

                int GuessNumber = int.Parse(Console.ReadLine());

                if (GuessNumber < 0 || GuessNumber > 100000)
                {
                    throw new ArgumentOutOfRangeException();
                }

                numberrandom.RandomFucntion(MiniNumber, MaxNumber, GuessNumber);
            }

            catch (ArgumentOutOfRangeException ex)
            {
                Console.WriteLine("error");

                Console.Write(ex.Message);

                Main();
            }

            catch (Exception ex)
            {
                Console.WriteLine("error");

                Console.Write(ex.Message);

                Main();
            }
        }
    }
}

參考資料:

https://www.geeksforgeeks.org/c-sharp-random-next-method/


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言